package com.gitee.huanminabc.fastboot.logback;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author huanmin
 * @date 2024/2/28
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class LogContainsFilter   extends AbstractMatcherFilter<ILoggingEvent> {
    //拦截规则,逗号分隔,必须全部匹配包含
    private String includes;
    private Level level;
    private String[] includeList;

    @Override
    public FilterReply decide(ILoggingEvent event) {
        //判断是否启动
        if (!isStarted()) {
            return FilterReply.NEUTRAL;
        }

        //判断日志级别, 如果小于设置的级别,则不打印
        if (!event.getLevel().isGreaterOrEqual(level)) {
            return FilterReply.NEUTRAL;
        }

        //判断是否匹配
        String message = event.getMessage();
        boolean pd=true;
        for (String include : includeList) {
            if (!message.contains(include)) {
                pd=false;
                break;
            }
        }
        if (pd) {
            return onMatch;//匹配则打印
        } else {
            return onMismatch;//不匹配则不打印
        }
    }

    public void start() {
        if (this.level != null) {
            super.start();
            //level不能为空
            if (level == null) {
                addError("level不能为空");
                return;
            }
            //includes不能为空
            if (includes == null || includes.isEmpty()) {
                addError("那么includes不能为空,逗号分隔");
                return;
            }
            includeList = includes.split(",");
        }
    }
}
